package com.example.gobang;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobRealTimeData;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.ValueEventListener;

public class ShowActivity extends AppCompatActivity {
    private MyWuZiQi wuziqi;
    private String objID;
    private Handler handler;
    private TextView tvRoom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);

        tvRoom=findViewById(R.id.tv_room);
        initHandler();
        final BmobRealTimeData rtd=new BmobRealTimeData();

        rtd.start(new ValueEventListener() {
            @Override
            public void onConnectCompleted(Exception e) {
                if (rtd.isConnected()){
                    rtd.subRowUpdate("GoBang",objID);
                }
            }

            @Override
            public void onDataChange(JSONObject jsonObject) {
                Log.e("dataChange",jsonObject.toString());
            }
        });

        if (rtd.isConnected()){
           rtd.subRowUpdate("GoBang",objID);
        }

        Bmob.initialize(ShowActivity.this,"1e2264f8ca359778399a79719c56d8f5");
        int TYPE=getIntent().getIntExtra("TYPE",0);
        wuziqi=findViewById(R.id.Mywuziqi);
        wuziqi.setTYPE(TYPE);
        if (TYPE==2){
            AlertDialog.Builder builder=new AlertDialog.Builder(this);
            final AlertDialog alertDialog=builder.create();
            View view=View.inflate(this,R.layout.activity_choose,null);
            alertDialog.setView(view);
            final Button btnCreate=view.findViewById(R.id.btn_create);
            final Button btnIn=view.findViewById(R.id.btn_in);

            btnCreate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final GoBang goBang=new GoBang();
                    goBang.setSomeoneIn(false);
                    goBang.setWhiteWin(false);
                    goBang.setCount(1);
                    goBang.setGameover(false);
                    goBang.setWhiteWinCount(0);
                    goBang.setWhite("");
                    goBang.setBlack("");
                    goBang.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if (e==null){
                                objID=goBang.getObjectId();
                                wuziqi.setObjID(objID);
                                alertDialog.dismiss();

                                wuziqi.setCurIsWhite(true);
                                wuziqi.setCanGo(true);
                                Message message=new Message();
                                message.what=1;
                                handler.sendMessage(message);
                            }else{
                                Log.e("create",e.toString());
                            }
                        }
                    });
                }
            });

            btnIn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    alertDialog.dismiss();
                    AlertDialog.Builder builder1=new AlertDialog.Builder(ShowActivity.this);
                    final AlertDialog alertDialog1=builder1.create();
                    View view1=View.inflate(ShowActivity.this,R.layout.activity_room_number,null);
                    alertDialog1.setView(view1);
                    final Button btnInRoom=view1.findViewById(R.id.btn_inRoom);
                    final EditText edtRoom=view1.findViewById(R.id.edt_room);
                    btnInRoom.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Integer room= Integer.valueOf(edtRoom.getText().toString());
                            Log.e("ShowActivity", String.valueOf(room));
                            BmobQuery<GoBang> query=new BmobQuery<GoBang>();
                            query.addWhereEqualTo("room",room);
                            query.findObjects(new FindListener<GoBang>() {
                                @Override
                                public void done(List<GoBang> list, BmobException e) {
                                    if (e==null){
                                        GoBang goBang=list.get(0);
                                        if (!goBang.getSomeoneIn()){
                                            Log.e("ShowActivity","成功进入房间");
                                            objID=goBang.getObjectId();
                                            wuziqi.setObjID(objID);
                                            wuziqi.setCurIsWhite(false);
                                            alertDialog1.dismiss();
                                            setRoomIn(objID);
                                        }else{
                                           Log.e("ShowActivity","已有用户加入");
                                        }
                                    }else{
                                        Log.e("inRoom",e.toString());
                                    }
                                }
                            });

                        }
                    });

                    alertDialog1.show();
                }
            });

            alertDialog.show();
        }

    }

    private void setRoomIn(String objID) {
        GoBang goBang=new GoBang();
        goBang.setSomeoneIn(true);
        goBang.update(objID,new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e==null){
                    Message message=new Message();
                    message.what=1;
                    handler.sendMessage(message);
                }
            }
        });
    }

    private void initHandler() {
        handler=new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if (message.what==1){
                    queryRoom();
                    return true;
                }else if (message.what==2){
                    Integer roomid= (Integer) message.obj;
                    tvRoom.setText(roomid.toString());
                    Toast.makeText(ShowActivity.this,"你的房间号为"+roomid,Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        });
    }

    private void queryRoom() {
        BmobQuery<GoBang> query=new BmobQuery<GoBang>();
        query.getObject(objID, new QueryListener<GoBang>() {
            @Override
            public void done(GoBang goBang, BmobException e) {
                if (e==null){
                    Message message=new Message();
                    message.what=2;
                    message.obj=goBang.getRoom();
                    handler.sendMessage(message);
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id=item.getItemId();
        if (id==R.id.action_setting){
            wuziqi.reStart();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
